package org.example.leetcode.core.service.impl.login;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.leetcode.common._enum.YesOrNoEnum;
import org.example.leetcode.common.domain.SysUser;
import org.example.leetcode.common.exception.MyException;
import org.example.leetcode.common.utils.TokenUtils;
import org.example.leetcode.core.dto.SysUserTokenDto;
import org.example.leetcode.core.service.LoginService;
import org.example.leetcode.core.service.SysUserService;
import org.example.leetcode.core.utils.RedisUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
@Service
public class PasswordLogin implements LoginService {
    @Resource
    RedisUtils redisUtils;
    @Resource
    SysUserService sysUserService;
    @Override
    @Transactional
    public SysUserTokenDto loginOrRegister(String phone, String password) {
        SysUser sysUser = sysUserService.getBaseMapper().selectOne(new LambdaQueryWrapper<SysUser>()
                .eq(SysUser::getPhone, phone));
        String token;
        String refreshToken;
        SysUserTokenDto sysUserTokenDto = new SysUserTokenDto();
        //第一次登录
        if(sysUser==null){
            SysUser newUser = new SysUser();
            newUser.setPhone(phone);
            newUser.setPassword(password);
            newUser.setIsNewUser(YesOrNoEnum.No.getCode());
            newUser.setNickName("小卡拉米");
            sysUserService.getBaseMapper().insert(newUser);
            //这里返回No,不用再去设计密码
            sysUserTokenDto.setIsNewUser(YesOrNoEnum.No.getCode());
            sysUserTokenDto.setNickName("小卡拉米");
            sysUserTokenDto.setPhone(phone);
            token=TokenUtils.createToken(newUser.getId(),phone);
            refreshToken=TokenUtils.createRefreshToken(newUser.getId(),phone);
            sysUserTokenDto.setToken(token);
        }
        else{
            //密码正确
            if(sysUser.getPassword().equals(password)){
                token=TokenUtils.createToken(sysUser.getId(),phone);
                refreshToken=TokenUtils.createRefreshToken(sysUser.getId(),phone);
                sysUserTokenDto.setToken(token);
                sysUserTokenDto.setPhone(phone);
                sysUserTokenDto.setIsNewUser(YesOrNoEnum.No.getCode());
                sysUserTokenDto.setNickName(sysUser.getNickName());
                sysUserTokenDto.setPic(sysUser.getPic());
        }
            //密码错误
            else{
                throw new MyException("密码错误");
            }
        }
        //保存refreshToken和accessToken
        redisUtils.setKey("ACCESS_TOKEN:"+phone,token,TokenUtils.TOKEN_VALID_TIME);
        redisUtils.setKey("REFRESH_TOKEN:"+phone,refreshToken,TokenUtils.TOKEN_VALID_TIME*7);
        return sysUserTokenDto;
    }

}
